Qt.include("oauth.js")

function makeTwitterAuthCall(userName, passWord, articleTitle, articleUrl) {
    var action = Const.TWITTER_ACCESS_TOKEN_URL;
    var accessor = { consumerSecret: Const.TWITTER_OAUTH_CONSUMER_SECRET, tokenSecret   : ""};
    var message = { action: action , method: "POST" , parameters: [] };
    var callerarg = []

    message.parameters.push(["x_auth_mode", "client_auth"]);
    message.parameters.push(["x_auth_password", passWord]);
    message.parameters.push(["x_auth_username", userName]);
    message.parameters.push(["oauth_consumer_key", Const.TWITTER_OAUTH_CONSUMER_KEY]);

    callerarg.push(["article_title", articleTitle])
    callerarg.push(["article_url", articleUrl])//console.log(JSON.stringify(callerarg))

    OAuth.completeRequest(message, accessor)
    doServiceRequest(message.method, action, OAuth.formEncode(message.parameters), twitterAuthCallback, null, callerarg, OAuth.getAuthorizationHeader("",message.parameters))
}

function twitterAuthCallback(responseText, params) {
    var results = OAuth.decodeForm(responseText);
    var twitter_auth_token = OAuth.getParameter(results, "oauth_token")
    var twitter_auth_token_secret = OAuth.getParameter(results, "oauth_token_secret")

    Storage.setSetting("TWITTER_OAUTH_TOKEN", twitter_auth_token)
    Storage.setSetting("TWITTER_OAUTH_TOKEN_SECRET", twitter_auth_token_secret)

    console.log(twitter_auth_token)
    console.log(twitter_auth_token_secret)

    feedItemPage.showReadItLaterSignIn("TWITTER", params[0][1], params[1][1], twitter_auth_token, twitter_auth_token_secret)
}

function cleanTwitterAuth() {
    Storage.setSetting("TWITTER_OAUTH_TOKEN", "")
    Storage.setSetting("TWITTER_OAUTH_TOKEN_SECRET", "")
    showBannerText(qsTr("Twitter Authorization Cleared Successfully"))
}

function cleanInstapaperAuth() {
    Storage.setSetting("INSTAPAPER_OAUTH_TOKEN", "")
    Storage.setSetting("INSTAPAPER_OAUTH_TOKEN_SECRET", "")
    showBannerText(qsTr("Instapaper Authorization Cleared Successfully"))
}

function cleanFacebookAuth() {
    Storage.setSetting("FACEBOOK_OAUTH_TOKEN", "")
    showBannerText(qsTr("Facebook Authorization Cleared Successfully"))
}

function cleanPocketAuth() {
    Storage.setSetting("READLATER_USEARNAME_READ_IT_LATER", "")
    Storage.setSetting("READLATER_PASSWORD_READ_IT_LATER", "")
    showBannerText(qsTr("Pocket Authorization Cleared Successfully"))
}

function tweetArticle(tweetText, token, tokenSecret) {
    var action = "https://api.twitter.com/1/statuses/update.json"

    var accessor = { consumerSecret: Const.TWITTER_OAUTH_CONSUMER_SECRET, tokenSecret   : tokenSecret};
    var message = { action: action , method: "POST" , parameters: [] };

    message.parameters.push(["status", tweetText]);
    message.parameters.push(["trim_user", "true"]);
    message.parameters.push(["include_entities", "true"]);
    message.parameters.push(["oauth_consumer_key", Const.TWITTER_OAUTH_CONSUMER_KEY]);
    message.parameters.push(["oauth_token", token]);

    OAuth.completeRequest(message, accessor)
    doServiceRequest(message.method, action, OAuth.formEncode(message.parameters), tweetArticleCallback, null, null, OAuth.getAuthorizationHeader("",message.parameters))
}

function tweetArticleCallback(responseText, Params) {
    showBannerText(qsTr("Your tweet was posted successfully"))
}

function sendArticleToInstapaper(title, url, token, tokenSecret) {
    var action = Const.INSTAPAPER_ADD_V2_URL

    var accessor = { consumerSecret: Const.INSTAPAPER_OAUTH_CONSUMER_SECRET, tokenSecret   : tokenSecret};
    var message = { action: action , method: "POST" , parameters: [] };

    message.parameters.push(["url", url]);
    message.parameters.push(["title", title]);
    message.parameters.push(["resolve_final_url", "1"]);
    message.parameters.push(["oauth_consumer_key", Const.INSTAPAPER_OAUTH_CONSUMER_KEY]);
    message.parameters.push(["oauth_token", token]);

    OAuth.completeRequest(message, accessor)
    doServiceRequest(message.method, action, OAuth.formEncode(message.parameters), sendArticleToInstapaperCallback, null, null, OAuth.getAuthorizationHeader("",message.parameters))
}

function sendArticleToInstapaperCallback(responseText, Params) {
    showBannerText(qsTr("Your article was posted successfully to Instapaper"))
}

function makeInstapaperAuthCall(userName, passWord, articleTitle, articleUrl) {
    var action = Const.INSTAPAPER_ACCESS_TOKEN_URL;
    var accessor = { consumerSecret: Const.INSTAPAPER_OAUTH_CONSUMER_SECRET, tokenSecret   : ""};
    var message = { action: action , method: "POST" , parameters: [] };
    var callerarg = []

    message.parameters.push(["x_auth_mode", "client_auth"]);
    message.parameters.push(["x_auth_password", passWord]);
    message.parameters.push(["x_auth_username", userName]);
    message.parameters.push(["oauth_consumer_key", Const.INSTAPAPER_OAUTH_CONSUMER_KEY]);

    callerarg.push(["article_title", articleTitle])
    callerarg.push(["article_url", articleUrl])//console.log(JSON.stringify(callerarg))

    OAuth.completeRequest(message, accessor)
    doServiceRequest(message.method, action, OAuth.formEncode(message.parameters), instapaperAuthCallback, null, callerarg, OAuth.getAuthorizationHeader("",message.parameters))
}

function instapaperAuthCallback(responseText, params) {
    var results = OAuth.decodeForm(responseText);
    var instapaper_auth_token = OAuth.getParameter(results, "oauth_token")
    var instapaper_auth_token_secret = OAuth.getParameter(results, "oauth_token_secret")

    Storage.setSetting("INSTAPAPER_OAUTH_TOKEN", instapaper_auth_token)
    Storage.setSetting("INSTAPAPER_OAUTH_TOKEN_SECRET", instapaper_auth_token_secret)
    sendArticleToInstapaper(params[0][1], params[1][1], instapaper_auth_token, instapaper_auth_token_secret)
}

function facebookStatusUpdate(statusText, articleUrl, oauthToken) {
    console.log("statusText: "+statusText)
    console.log("articleUrl: "+articleUrl)
    console.log("oauthToken: "+oauthToken)
    var action = "https://graph.facebook.com/me/feed"
    //var message = statusText + " " + articleUrl

    var postUrlString = action + "?access_token="+encodeURIComponent(oauthToken)+"&message="+encodeURIComponent(statusText)+"&link="+encodeURIComponent(articleUrl)
    //var parameters = []
    doServiceRequest("POST", postUrlString, null, facebookStatusUpdateCallback, null, null, null)
    //Storage.setSetting("FACEBOOK_OAUTH_TOKEN","");
}

function facebookStatusUpdateCallback (responseText, params) {
    //console.log("Response (Facebook): "+responseText)
    showBannerText(qsTr("Your post was shared on Facebook successfully"))
}

function doServiceRequest(method, url, params, callback, caller, callerarg, authHeader) {
    var req = new XMLHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //console.log("From Twitter:"+req.responseText)
            if(req.status == 200) callback(req.responseText, callerarg)
            else if (req.status == 401) {
                if(url.indexOf("https://api.twitter.com/1/") > -1 ) cleanTwitterAuth()
                else if (url.indexOf("https://graph.facebook.com/me/feed") > -1) cleanFacebookAuth()
                showBannerText(qsTr("Authentication Error: Please reauthorize with login"))
            } else if (req.status == 400 & url.indexOf("https://graph.facebook.com/me/feed") > -1 ) {
                cleanFacebookAuth()
                showBannerText(qsTr("Authentication Error: Please reauthorize with login"))
            } else showBannerText(qsTr("Unknows Error: Please retry after some time"))
        }
    }

    req.open(method, url, true);
    if(authHeader != null && (url.indexOf("https://graph.facebook.com/me/feed") > -1)) req.setRequestHeader("Authorization", authHeader);
    req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    req.send(params);
}

function showBannerText(textToDisplay) {
    pageInfoBanner.text = textToDisplay
    applicationPlatform == "symbian" ? pageInfoBanner.open() : pageInfoBanner.show()
}
